import Layer from '../../core/Layer';

export default class extends Layer {
    constructor(canvas, style) {
        super(canvas, style);
        this.series = [];
        this.xAxis = null;
        this.yAxis = null;
        this.count = style.count || 30;
        this.shift = style.shift || 0;
    }

    setXAxis(xAxis) {
        this.xAxis = xAxis;
    }

    setYAxis(yAxis) {
        this.yAxis = yAxis;
    }

    addSeries(line) {
        this.series.push(line);
    }

    build(painter) {
        this.childs.splice(0);
        let max = Number.MIN_VALUE;
        let min = Number.MAX_VALUE;
        for (let i = 0; i < this.series.length; i++) {
            this.series[i].getMinMax();
            if (min > this.series[i].min) {
                min = this.series[i].min;
            }
            if (max < this.series[i].max) {
                max = this.series[i].max;
            }
        }
        let absValue = Math.abs(max) > Math.abs(min) ? Math.abs(max) : Math.abs(min);
        let axisMin = 0;
        let axisMax = 0;
        if (min >= 0) {
            axisMax = absValue;
            axisMin = 0;
        } else if (max > 0) {
            axisMax = absValue;
            axisMin = - absValue;
        } else {
            axisMax = 0;
            axisMin = - absValue;
        }
        this.yAxis.max = axisMax;
        this.yAxis.min = axisMin;
        this.yAxis.height = this.height - this.xAxis.height;
        this.yAxis.bottom = this.xAxis.height;
        let xStep = (this.width - this.yAxis.width) / this.count;
        this.xAxis.width = this.width - this.yAxis.width;
        this.xAxis.left = this.yAxis.width + xStep / 2;
        this.xAxis.xStep = xStep;
        this.xAxis.cols = this.count;
        this.addChild(this.yAxis);
        this.addChild(this.xAxis);

        let barWidth = Math.round((xStep - 2 * this.gutter) / this.series.length);
        let yStep = (this.height - this.xAxis.height) / (axisMax - axisMin);
        for (let i = 0; i < this.series.length; i++) {
            this.series[i].left = Math.round(this.yAxis.width + i * barWidth + this.gutter);
            this.series[i].xStep = Math.round(xStep);
            this.series[i].base = (0 - axisMin) * yStep + this.xAxis.height;
            this.series[i].yStep = yStep;
            this.series[i].barWidth = barWidth;
            this.series[i].width = this.width - this.yAxis.width;
            this.series[i].height = this.yAxis.height;
            this.addChild(this.series[i]);
        }

    }
}
